import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './tianditu.less'
import { loadJs } from '../../utils/tools'
const ready = loadJs('http://api.tianditu.gov.cn/api?v=4.0&tk=6c7e4c383394453f5a42bdc42d9e7554')
export interface TiandituProps {
  width: number | string
  height: number | string
  lnglat?: [number, number]
  onPositionPick?: (evt: any) => void
  onPolygonPick?: (evt: any) => void
}
export default function (props: TiandituProps) {
  const containerRef = useRef<HTMLDivElement>(null)
  const mapRef = useRef<any>(null)
  const cpRef = useRef<any>(null)
  const polygonRef = useRef<any>(null)
  useEffect(() => {
    ready.then(() => {
      const container = containerRef.current
      if (!container) return
      const lng = props.lnglat?.[0] || 116.40769
      const lat = props.lnglat?.[1] || 9.89945
      //初始化地图对象
      const map = new window.T.Map(container, {
        projection: 'EPSG:4326'
      })
      //设置显示地图的中心点和级别
      map.centerAndZoom(new window.T.LngLat(lng, lat), 12)
      mapRef.current = map
    })
  }, [])

  useEffect(() => {
    const lng = props.lnglat?.[0]
    const lat = props.lnglat?.[1]
    if (!lng || !lat) return
    const map = mapRef.current
    if (!map) return
    map.centerAndZoom(new window.T.LngLat(lng, lat), 12)
  }, [props.lnglat])

  // 开启坐标拾取
  const openCoordinatePickup = () => {
    if (cpRef.current || !mapRef.current) return
    const cp = new window.T.CoordinatePickup(mapRef.current, {
      callback: (evt) => {
        props.onPositionPick?.(evt)
      }
    })
    cp.addEvent()
    cpRef.current = cp
  }

  // 关闭坐标拾取
  const closeCoordinatePickup = () => {
    if (!cpRef.current) return
    cpRef.current.removeEvent()
    cpRef.current = null
  }

  // 开启多边形工具
  const openPolygonTool = () => {
    if (!mapRef.current) return
    closeCoordinatePickup()
    if (polygonRef.current) polygonRef.current.close()
    const polygon = new window.T.PolygonTool(mapRef.current)
    polygon.open()
    polygon.addEventListener('draw', (evt) => {
      props.onPolygonPick?.(evt.currentLnglats)
    })
    polygonRef.current = polygon
  }

  // 清空绘制的多边形
  const clearPolygonTool = () => {
    if (mapRef.current) mapRef.current.clearOverLays()
  }

  /** 运行时 */
  return (
    <div className={styles.mapContainer} style={{ width: props.width, height: props.height }}>
      <div className={styles.map} ref={containerRef} />
      <div className={styles.tools}>
        <div className={styles.toolsBtn} onClick={openCoordinatePickup}>
          坐标拾取器
        </div>
        <div className={styles.toolsBtn} onClick={openPolygonTool}>
          多边形工具
        </div>
        <div className={styles.toolsBtn} onClick={clearPolygonTool}>
          清空
        </div>
      </div>
    </div>
  )
}
